#!/user/bin/python3
# @Author:  LSY
# @Date:    2020/9/14
import logging

from flask import Blueprint, request, current_app
import json
import datetime

from app.models.po.hanfan.hanfan_predict_po import HanFanPredictPO
from app.services.business import hanfan_biz_service
from app.services.business.hanfan_biz_service import get_hanfan_history_between, get_content_change_data, \
    prediction_data, param_dist_dict
from app.utils import string_util
from app.utils.sys_utils import get_time_round_and_adjust, GaoLuEncoder
from app.controllers.response.response import SuccessResult
from typing import List, Dict

bp = Blueprint('hanfan', __name__, url_prefix="/api/v1/hanfan")
hanfan_bp = bp


@hanfan_bp.route("/prediction/info", methods=['GET'])
def prediction_info():
    end = request.args.get('end')
    if end is None:
        end = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    end_time = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S")
    end_time = get_time_round_and_adjust(end_time, step=0, round_level='hour')
    ret = prediction_data(end_time)
    return SuccessResult(detail=ret, encoder=GaoLuEncoder)

@hanfan_bp.route("/current/info", methods=['GET'])
def current_info():
    end = request.args.get('end')
    if end is None:
        end = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    end_time = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S")
    end_time = get_time_round_and_adjust(end_time, step=0, round_level='hour')
    record: HanFanPredictPO = hanfan_biz_service.get_hanfan_result_one(end_time)
    return SuccessResult(detail=record, encoder=GaoLuEncoder)


@hanfan_bp.route('/hanFanParamDist', methods=['GET'])
# @login_required
def hanfan_param_dist():
    """
    提取各参数历史分布
    想要自主用start 和 end 选取时间段，必须设置refresh = True
    :return:
    """
    start = request.args.get('start')
    end = request.args.get('end')
    refresh = request.args.get('refresh')

    if string_util.is_not_empty(start) and string_util.is_not_empty(end):
        start = datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S")
        end = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S")
    else:
        start = None
        end = None

    ret_dict = param_dist_dict(start, end, refresh)
    if ret_dict is None:
        return SuccessResult(detail=None)
    param_data_format = {}
    for param_name in ret_dict.keys():
        x_list = []
        y_list = []
        param_item = ret_dict.get(param_name)
        for key, value in param_item.items():
            """
            key 本来就是有序的，若无序，需排序
            """
            x_list.append(key)
            y_list.append(value)
        param_data_format[param_name] = [x_list, y_list]
    return SuccessResult(detail=param_data_format)


@hanfan_bp.route("/contentChange/data", methods=['GET'])
def content_change_data():
    start = request.args.get('start')
    end = request.args.get('end')
    if start is None or end is None:
        now = datetime.datetime.now()
        start_time = get_time_round_and_adjust(now, step=0, round_level='hour')
        end_time = get_time_round_and_adjust(start_time, step=1, round_level='hour')
    else:
        start_time = datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S")
        end_time = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S")

    ret = get_content_change_data(start_time, end_time, left="close", right="open",
                                  order_by=HanFanPredictPO.GMT_CREATE.asc())
    return SuccessResult(detail=ret, encoder=GaoLuEncoder)


@hanfan_bp.route("/fuelTracking/data", methods=['GET'])
def fuel_tracking_data():
    end = request.args.get('end')
    params = request.args.get('params')
    if end is None:
        end = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    end_time = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S")
    end_time = get_time_round_and_adjust(end_time, step=0, round_level='hour')
    ret = hanfan_biz_service.fuel_tracking(end_time, params)
    return SuccessResult(detail=ret, encoder=GaoLuEncoder)


@hanfan_bp.route('/coreData/info', methods=['POST', 'GET'])
def get_core_data():
    json_data = json.loads(request.get_data())
    start = json_data.get('start')
    end = json_data.get('end')
    params = json_data.get('params')

    if start is None or end is None:
        now = datetime.datetime.now()
        start_time = get_time_round_and_adjust(now, step=0, round_level='hour')
        end_time = get_time_round_and_adjust(start_time, step=1, round_level='hour')
    else:
        start_time = datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S")
        end_time = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S")

    his_ret = get_hanfan_history_between(start_time, end_time, left="close", right="open",
                                         order_by=HanFanPredictPO.GMT_CREATE.asc())
    ret = {}
    core_params = current_app.config['HANFAN_CORE_PARAMS'] if params is None else params + ['DateTime']
    for param in core_params:
        ret[param] = []

    for po in his_ret:
        for param in core_params:
            ret[param].append(po.__getattribute__(param))
    return SuccessResult(detail=ret, encoder=GaoLuEncoder)


@hanfan_bp.route('/statistics/info', methods=['GET'])
def get_statistics_info():
    start = request.args.get('start')
    end = request.args.get('end')
    refresh = request.args.get('refresh')

    if string_util.is_not_empty(start) and string_util.is_not_empty(end):
        start = datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S")
        end = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S")
    else:
        start = None
        end = None

    ret_dict = param_dist_dict(start, end, refresh)
    # 获取最近一个时刻的值
    now_time = datetime.datetime.now()
    before_time = now_time - datetime.timedelta(hours=2)

    entity: HanFanPredictPO = hanfan_biz_service.get_hanfan_fisrt_result(before_time, now_time,
                                                                         order_by=HanFanPredictPO.GMT_CREATE.desc())
    ret = dict(hf=0,
               v2o5=0)

    if ret_dict is not None:
        for param_name in ['CG_LT_GL_GL04_Yuanranliao_Ore_V2O5','CURRENT_HF']:
            x_list = []
            y_list = []
            param_item = ret_dict.get(param_name)
            for key, value in param_item.items():
                """
                key 本来就是有序的，若无序，需排序
                """
                x_list.append(key)
                y_list.append(value)
            ret[param_name] = [x_list, y_list]

    if entity:
        ret['hf'] = entity.CURRENT_HF,
        ret['v2o5'] = entity.CG_LT_GL_GL04_Yuanranliao_Ore_V2O5

    return SuccessResult(detail=ret, encoder=GaoLuEncoder)


@hanfan_bp.route('/autoScore', methods=['GET'])
def hanfan_auto_score(inner_call=None):
    end = request.args.get('end')
    if end is None:
        end = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    end_time = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S")
    end_time = get_time_round_and_adjust(end_time, step=0, round_level='hour')
    start_time = get_time_round_and_adjust(end_time, step=-1, round_level='hour')
    ret = hanfan_biz_service.auto_score(start_time, end_time)
    return SuccessResult(detail=ret)
